﻿using System;
using ECommerce.Web.Services.Cookies;

namespace ECommerce.Web.Services.ShoppingSessions
{
    public class ShoppingSession : IShoppingSession
    {
        private const string ShopperCookieKey = "ECommerce.Shopper";

        private readonly ICookieContainer cookieContainer;

        public ShoppingSession(ICookieContainer cookieContainer)
        {
            this.cookieContainer = cookieContainer;
        }

        public Guid GetShopperToken()
        {
            string value = this.cookieContainer.Get(ShopperCookieKey);

            if (String.IsNullOrEmpty(value))
            {
                return IssueShopperToken();
            }

            try
            {
                return new Guid(value);
            }
            catch (FormatException)
            {
                return IssueShopperToken();
            }
        }

        private Guid IssueShopperToken()
        {
            Guid token = Guid.NewGuid();

            this.cookieContainer.Set(ShopperCookieKey, Convert.ToString(token), SystemTime.Now().Date.AddYears(1));

            return token;
        }
    }
}
